var map;
var images = [
  "http://maps.google.com/mapfiles/marker.png",
  "http://maps.google.com/mapfiles/dd-start.png",
  "http://maps.google.com/mapfiles/dd-end.png"
];

var Point = {
    form: null,
    stop: null,
    _marker: null,
    _markers: {},
    
    getForm: function()
    {
        if (this.form == null) {
            this.form = $('#form_point');
        }
        return this.form;
    },

    getGrid: function()
    {
        if (this.grid == null) {
            this.grid = $('#gbox_points_grid');
        }
        return this.grid;
    },

    showForm: function()
    {
        Point.getGrid().hide();
        Point.getForm().show();
    },

    showGrid: function()
    {
        Point.getForm().hide();
        Point.getGrid().show();
    },

    follow: function()
    {
        if (Point._marker != null) {
            alert('Save or Cancel current item before this action.');
            return;
        }
        var marker;
        var dog = true;
        var noMore = false;
        var markerClick;

        var mouseMove = google.maps.event.addListener(map, 'mousemove', function(cursorPoint){
            if (!noMore) {
                marker = new google.maps.Marker({
                     position: cursorPoint.latLng
                    ,draggable:true
                    ,autoPan:false
                    ,map: map
                    //,icon: images[imageInd]
                });
                markerClick = google.maps.event.addListener(marker, 'click', function(e){
                    if (dog) {
                        dog = false;
                        google.maps.event.removeListener(mouseMove);
                        google.maps.event.removeListener(mapClick);
                        google.maps.event.removeListener(markerClick);
                        Point.create(marker);
                    }
                });
                noMore = true;
                // This function deletes the marker when dragged outside map
                google.maps.event.addListener(marker, 'drag', function(markerPoint){
                    $('#coord_lat').val(markerPoint.latLng.lat());
                    $('#coord_lng').val(markerPoint.latLng.lng());
                });
                Point._marker = marker;
            }
            if (dog) {
                marker.setPosition(cursorPoint.latLng);
            }
        });

        var mapClick = google.maps.event.addListener(map, 'click', function(cursorPoint){
            if (dog) {
                dog = false;
                google.maps.event.removeListener(mouseMove);
                google.maps.event.removeListener(mapClick);
                google.maps.event.removeListener(markerClick);
                Point.create(marker);
            }
        });
    },

    create: function(marker)
    {
        this._marker = marker;
        this.resetForm();
        $('#coord_lat').val(marker.getPosition().lat());
        $('#coord_lng').val(marker.getPosition().lng());
        this.showForm();
        $("#tabs").tabs('select', 1);
    },

    resetForm: function()
    {
        $('#point_pid').val(0);
        this.getForm().get(0).reset();
    },

    onSubmit: function()
    {
        var form = Point.getForm();
        $.ajax({
            type: 'post',
            url: form.attr('action'),
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.errors) {
                    alert(response.errors.join("\n"));
                    return;
                }
                Point.showGrid();
                if (Point._marker && !Point._marker.point_pid) {
                    Point._marker.setMap(null);
                } else {
                    Point._marker.setDraggable(false);
                }
                Point._marker = null;
                Point.reloadList();
            }
        });
        return false;
    },

    reloadList: function()
    {
        $.getJSON(BASE_URL + '/map/point/list', function(response) {
            if (response.errors) {
                alert(response.errors.join("\n"));
                return;
            }
            var data = response.data, item, marker;
            for (var i in data) {
                item = data[i];
                if (Point._markers[item.point_pid]) {
                    // update exists marker
                    marker = Point._markers[item.point_pid];
                    // update position
                    var cur_pos = marker.getPosition();
                    if (cur_pos.lat() != item.coord_lat || cur_pos.lng() != item.coord_lng) {
                        marker.setPosition(
                            new google.maps.LatLng(item.coord_lat, item.coord_lng)
                        );
                    }
                    marker.setTitle(item.stop_name);
                } else {
                    // add new marker
                    var pos = new google.maps.LatLng(item.coord_lat, item.coord_lng);
                    marker = new google.maps.Marker({
                         position: pos
                        ,draggable: false
                        ,autoPan: false
                        ,map: map
                        ,title: item.stop_name
                        //,icon: images[imageInd]
                    });
                    google.maps.event.addListener(marker, 'click', Point.onMarkerClick);
                    google.maps.event.addListener(marker, 'drag', Point.onMarkerDrag);
                    Point._markers[item.point_pid] = marker;
                    marker.point_pid = item.point_pid;
                }
            }
        });
    },

    onMarkerClick: function(e)
    {
        if (Point.getForm().css('display') == 'block') {
            return;
        }
        this.setDraggable(true);
        Point.edit(this.point_pid);
        Point._marker = this;
    },

    edit: function(id)
    {
        Point.resetForm();
        $.getJSON(BASE_URL + '/map/point/load/id/' + id, function(response){
            if (response.errors) {
                alert(response.errors.join("\n"));
                return;
            }
            var input;
            for (var i in response) {
                input = $('#' + i);
                if (input.attr('type') == 'checkbox') {
                    if (response[i] == 1) {
                        input.attr('checked', true);
                    }
                } else {
                    input.val(response[i]);
                }
            }
            
            Point.showForm();
        });
    },

    onMarkerDrag: function(markerPoint)
    {
        $('#coord_lat').val(markerPoint.latLng.lat());
        $('#coord_lng').val(markerPoint.latLng.lng());
    },

    onCancel: function()
    {
        Point.showGrid();
        if (!Point._marker.point_pid) {
            Point._marker.setMap(null);
        }
        Point._marker.setDraggable(false);
        Point._marker = null;
        Point.reloadList();
    },

    getStop: function(id)
    {
        return this._markers[id];
    }
}